<template>
  <view class="pay">
    <!-- 1 收货地址 -->
    <view class="address u-p-20">
      <view
        v-if="!addressInfo"
        class="address-btn u-flex u-row-center"
      >
        <u-button
          shape="circle"
          type="error"
          plain
          size="medium"
          :custom-style="{ backgroundColor: '#fff!important' }"
          @click="handleChooseAddress"
        >获取收货地址</u-button>
      </view>

      <view
        v-else
        class="address-detail"
      >
        <view class="address-detail">{{detail}}</view>
        <view class="address-user">{{addressInfo.userName  }} {{addressInfo.telNumber  }}</view>
      </view>
    </view>

    <u-line color="#eee"></u-line>

    <!-- 2 已选商品 -->
    <view class="goods-list u-p-15">
      <view class="goods-list-title">已选商品</view>
      <view class="goods-list-content">
        <view
          v-for="item in checkedCartList"
          :key="item.goods_id"
          class="cart-item"
        >
          <!-- 2 图片 -->
          <view class="goods-img">
            <u-image
              width="191rpx"
              height="191rpx"
              :src="item.goods_small_logo"
            ></u-image>
          </view>
          <!-- 3 信息 -->
          <view class="goods-info">
            <!-- 名称 -->
            <view class="goods-name u-line-2">{{item.goods_name}}</view>
            <!-- 价格和数量 -->
            <view class="goods-price-num">
              <view class="goods-price">￥{{item.goods_price}}</view>
              <view class="goods-num-tool">
                <view class="goods-vnum">x {{item.num}}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 2 统计 -->
    <view class="statistics">
      <view class="all-price"> 合计: <text>￥ {{totalPrice}}</text> </view>
      <view class="all-count">
        <u-button
          type="error"
          shape="circle"
          @click="handlePay"
        >去支付({{totalCount}})</u-button>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      // 收货地址信息
      addressInfo: null,
    };
  },
  computed: {
    ...mapGetters("cart", ["checkedCartList", "totalPrice", "totalCount"]),
    // 用户的详细收货地址
    detail() {
      //       cityName: "广州市"
      // countyName: "海珠区"
      // detailInfo: "新港中路397号"
      // errMsg: "chooseAddress:ok"
      // nationalCode: "510000"
      // postalCode: "510000"
      // provinceName: "广东省"
      // telNumber: "020-81167888"
      // userName: "张三"
      if (!this.addressInfo) return "";
      const { provinceName, cityName, countyName, detailInfo } =
        this.addressInfo;
      return provinceName + cityName + countyName + detailInfo;
    },
  },

  methods: {
    // 获取收货地址信息
    async handleChooseAddress() {
      const [err, addressInfo] = await uni.chooseAddress();
      if (err) {
        console.log(err);
      } else {
        this.addressInfo = addressInfo;
        console.log(this.addressInfo);
      }
    },

    // 点击支付按钮
    async handlePay() {
      // 0 判断用户还没有选择收货地址
      if (!this.addressInfo) {
        uni.showToast({
          title: "您还没有选择收货地址",
          icon: "none",
        });

        return;
      }

      // 1 调用小程序的api 获取当前用户信息
      const [err1, res1] = await uni.getUserProfile({
        desc: "用来给用户提供更好的服务",
      });
      //  获取接口要的用户信息

      const { encryptedData, rawData, iv, signature } = res1;
      // console.log(encryptedData, rawData, iv, signature);

      // 2 执行微信的登录 login 获取临时登录凭据
      const [err2, res2] = await uni.login();
      const { code } = res2;

      // 3 向后端来获取 token
      const res3 = await this.$u.http.post("/users/wxlogin", {
        encryptedData,
        rawData,
        iv,
        signature,
        code,
      });
      const { token } = res3;

      // 4 创建订单

      // 4.1 构造 请求体的参数
      // order_price	是	string	订单总价格
      // consignee_addr	是	string	收货地址
      // goods	是	Array	订单数组
      const orderParams = {
        order_price: this.totalPrice,
        consignee_addr: this.detail,
        goods: this.checkedCartList.map((goods) => ({
          goods_id: goods.goods_id,
          goods_number: goods.num,
          goods_price: goods.goods_price,
        })),
      };

      // 4.2  开始发送请求
      const res4 = await this.$u.http.post("/my/orders/create", orderParams, {
        Authorization: token,
      });
      console.log(res4);
      // 4.3 获取到了订单编号
      const { order_number } = res4;

      // 5 发起支付流程 获取支付参数
      const res5 = await this.$u.http.post(
        "/my/orders/req_unifiedorder",
        { order_number },
        {
          Authorization: token,
        }
      );

      // console.log(res5);
      const { pay } = res5;

      // 6 开始调起微信支付
      uni.requestPayment(pay);
    },
  },
};
</script>

<style lang="scss">
.pay {
  padding-bottom: 111rpx;
}
.cart-item {
  display: flex;
  padding: 10rpx;
  border-bottom: 1rpx solid #ccc;

  .goods-img {
    flex: 2;

    display: flex;
    align-items: center;
    justify-content: center;
  }

  .goods-info {
    color: #666;
    flex: 3;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    .goods-name {
    }

    .goods-price-num {
      display: flex;
      justify-content: space-between;
      .goods-price {
        color: $uni-them-color;
      }

      .goods-num-tool {
        width: 140rpx;
        height: 40rpx;

        display: flex;
        justify-content: flex-end;

        .goods-vnum {
        }
      }
    }
  }
}
.statistics {
  position: fixed;
  background-color: #fff;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 100;
  border-top: 1rpx solid #ccc;
  display: flex;
  align-items: center;
  padding: 15rpx;
  .all-price {
    flex: 1;
    color: #666;
    text {
    }
  }

  .all-count {
  }
}
</style>